import { login, getUserProfile } from '@/api/user'

const state = {
  token: null,
  profile: {}
}

const mutations = {
  setToken(state, token) {
    state.token = token
  },
  setProfile(state, profile) {
    state.profile = profile
  }
}

const actions = {
  async login({ commit }, payload) {
    try {
      const response = await login(payload)
      commit('setToken', response.data.token)
      return response
    } catch (error) {
      throw error
    }
  },
  async fetchUserProfile({ commit }) {
    try {
      const response = await getUserProfile()
      commit('setProfile', response.data)
      return response
    } catch (error) {
      throw error
    }
  }
}

const getters = {
  isLoggedIn(state) {
    return !!state.token
  },
  userProfile(state) {
    return state.profile
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
